import React, { useState, useRef, useEffect } from "react"
import { Link } from "umi"
import { useLocation, useHistory } from "react-router"
import { Button, Input, message, Modal, Checkbox, TreeSelect, Tree, Empty, Spin } from "antd"
const { TreeNode } = TreeSelect
const { Search } = Input
import { LoadingOutlined, SearchOutlined } from "@ant-design/icons"
import { sysDeptTreeApi, sysDeptOut, userPopApi, userPopinPam, userPopOut } from "@/services/components/treeGroupMemberSearch"
import { DataNode } from "rc-tree-select/lib/interface"

import "./importCss.less"

interface IProps {
  isModalVisible: boolean // 是否显示弹框
  setIsModalVisible: (boolean: boolean) => void // 设置是否隐藏函数
  getChildParam: (arr: Array<userPopOut>) => void // 点击确认按钮，把选中的用户传值
  isSelectMultiple?: boolean   // 是否多选 默认多选，true单选  false多选
}

/**
 * 搜索组员弹框  
 * 树形版本组员搜索，
 * 左边是科室列表 右边是 医生用户列表
 * 暂时是多选的
 * 
 *  */
const treeSelectGroupMemberSearch = (props: IProps) => {
  // console.log("IProps", props)

  const [loading, setLoading] = useState<boolean>(false)
  const [checkArr, setCheckArr] = useState<Array<userPopOut>>([])
  const [width, setWidth] = useState<number | string>("40%") // 弹框宽度
  const [treeDataDept, setTreeDataDept] = useState<DataNode | sysDeptOut | any>() // 树形科室


  const [currentValue, setCurrentValue] = useState<string>("") // 指定当前选中条目
  const [unfolds, setUnfolds] = useState<Array<any>>([])

  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true)
  const [expandedKeys, setExpandedKeys] = useState<Array<any>>([])


  const [name, setName] = useState<string>("")
  const [roleKey, setRoleKey] = useState<string>("DOCTOR")
  const [deptId, setDeptId] = useState<number | null>(null)

  const [userList, setUserList] = useState<Array<userPopOut>>([]) // 用户列表



  // 点击确认传值
  const handleOk = () => {
    // setIsModalVisible(false)
    props.getChildParam(checkArr)
    props.setIsModalVisible(false)
  }
  // 点击取消 
  const handleCancel = () => {
    props.setIsModalVisible(false)
  }


  // 选中树节点时调用此函数
  const onSelect = (selectedKeys: React.Key[], e: any) => {
    console.log("selected", selectedKeys, e)
    let pam: userPopinPam = {
      name,
      roleKey,
      deptId: e.node.id,
    }
    setDeptId(e.node.id)
    userPopApiFn(pam)

  }


  // Checkbox.Group  选中事件  多选用
  const onChangeCheckbox = (arr: Array<any>) => {
    console.log("选中用户", arr)

    if (arr.length >= 1) {
      setCheckArr(arr)
    }
  }

  const treeData = [
    {
      title: "parent 1",
      key: "0",
      children: [
        {
          title: "parent88888",
          key: "3254555555",
          selectable: false,
          children: [
            {
              title: "leaf",
              key: "34324",
              children: [
                {
                  title: "leaf",
                  key: "1",
                },
                {
                  title: "leaf",
                  key: "2",
                  children: [
                    {
                      title: "leaf4543534534534534545",
                      key: "3",
                    },
                    {
                      title: "leaf45345345345345345",
                      key: "4",
                    },
                  ]
                },
              ]
            },
            {
              title: "leaf",
              key: "0-0-0-1",
            },
          ],
        },

        {
          title: "52",
          key: "435435",
          children: [{ title: <span style={{ color: "#1890ff" }}>sss</span>, key: "45435" }],
        },
        {
          title: "777",
          key: "4534345",
          children: [{ title: <span style={{ color: "#1890ff" }}>sss</span>, key: "4354350" }],
        },
        {
          title: "6666",
          key: "5443435",
          children: [{ title: <span style={{ color: "#1890ff" }}>sss</span>, key: "656546" }],
        },
        {
          title: "parent3333",
          key: "32323",
          children: [{ title: <span style={{ color: "#1890ff" }}>sss</span>, key: "03223" }],
        },
      ],
    },
  ]

  // 获取需要展开的节点
  // eslint-disable-next-line max-params
  const getKey = (data: any, cun: any, value: any, expandedKeys: any) => {
    // eslint-disable-next-line array-callback-return
    data.map((item: any, i: any) => {
      // eslint-disable-next-line no-param-reassign
      cun = cun + "," + item.key
      if (String(item.title).indexOf(value) > -1) {
        expandedKeys.push(...cun.split(","))
      }
      if (item.hasOwnProperty("children")) {
        getKey(item.children, cun, value, expandedKeys)
      }
    })
  }

  const searchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target
    // setSearchValue(e.target.value)
    const expandedKeys: any = []

    // eslint-disable-next-line array-callback-return
    treeData.map((item: any) => {
      let cun = item.key
      getKey(item.children, cun, value, expandedKeys)
    })
    setAutoExpandParent(true)
    setUnfolds([...new Set(expandedKeys)])
    console.log(expandedKeys)
  }

  // 必须配合展开事件
  const onExpand = (expandedKeys: any) => {
    console.log("onExpand", expandedKeys)
    setExpandedKeys(expandedKeys)
    setAutoExpandParent(false)
  }

  // 姓名
  const nameOnChange = (e: any) => {
    setName(e.target.value)
  }


  // 搜索按钮
  const searFn = () => {
    let pam: userPopinPam = {
      name,
      roleKey,
      deptId
    }
    userPopApiFn(pam)
  }


  // 左边视图渲染
  const LeftTreeView = () => {
    if (!treeDataDept || treeDataDept.length === 0) {
      return <Empty className="emptyClass" image={Empty.PRESENTED_IMAGE_SIMPLE} />
    }

    let leftcon = (
      <Tree
        expandedKeys={expandedKeys}
        onExpand={onExpand}
        autoExpandParent={autoExpandParent}

        onSelect={onSelect}
        treeData={treeDataDept}
      />
    )
    return leftcon
  }

  // 获取树形科室列表
  const sysDeptTreeList = async () => {
    setLoading(true)
    const [err, res] = await sysDeptTreeApi()
    // console.log(111, res.data)
    if (err) {
      setLoading(false)
      return message.error(err.message)
    }
    if (res.data === null && JSON.stringify(res.data) === "{}") {
      return false
    }

    let data = forTreeDate(res.data)
    console.log("组合后：", data)

    let pam: userPopinPam = {
      name,
      roleKey,
      deptId: data[0].id,
    }
    setDeptId(data[0].id)
    userPopApiFn(pam)

    setExpandedKeys([data[0].id])
    setAutoExpandParent(false)

    setTreeDataDept(data)
    setLoading(false)
  }

  // 获取右侧对应树的用户列表
  const userPopApiFn = async (pam: userPopinPam) => {
    setLoading(true)
    // let pam2: userPopinPam = {name,roleKey,deptId}
    const [err, res] = await userPopApi(pam)
    console.log(111, res)
    if (err) {
      setLoading(false)
      return message.error(err.message)
    }
    res.data.forEach((item: any) => {
      item.checked = false
    })
    setUserList(res.data)
    setLoading(false)
  }


  /* 递归部门树形结构
  value?: RawValueType;
  title?: React.ReactNode;
  label?: React.ReactNode;
  key?: Key;
  disabled?: boolean;
  disableCheckbox?: boolean;
  checkable?: boolean;
  children?: DataNode[];
  */
  const forTreeDate = (data: sysDeptOut) => {
    data.label = data.code
    data.key = data.id
    data.title = data.name

    if (data.childDept && data.childDept.length >= 1) {
      data.children = data.childDept
      data.childDept.forEach((item: sysDeptOut) => {
        forTreeDate(item)
      })
    } else {
      data.children = []
    }
    return [data]
  }

  // 渲染用户列表
  const ShowUserList = () => {
    let con = null
    if (!userList || userList.length === 0) {
      con = <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      return con
    }
    con = <>
      {
        userList.map((item: userPopOut) => {
          return (
            <label key={item.id} >
              <div className="treeSelectGroupMemberSearch-itemWrap">
                <div className="treeSelectGroupMemberSearch-itemLeft">
                  <div><img className="img" src={item.photo} /></div>
                  <div className="treeSelectGroupMemberSearch-spanWrap">
                    <div> <span className="treeSelectGroupMemberSearch-span1" >{item.name}</span> <span title={item.deptName} className="treeSelectGroupMemberSearch-span2" >{item.deptName}</span> </div>
                    <div title={item.hospitalName} className="treeSelectGroupMemberSearch-span3" >{item.hospitalName}</div>
                  </div>
                </div>
                <div>
                  <Checkbox onChange={CheckboxChange} checked={item.checked} value={item} />
                </div>
              </div>
            </label>
          )
        })
      }
    </>
    return con
  }

  // 单选用
  const CheckboxChange = (e: any) => {

    let currentObj = e.target.value
    userList.map((item: userPopOut) => {
      item.checked = false
      if (currentObj.id === item.id) {
        item.checked = true
      }
      return item
    })
    setCheckArr([currentObj])
    setUserList([...userList])
  }


  // 初始化
  useEffect(() => {
    sysDeptTreeList()
  }, [])



  return (
    <div className="treeSelectGroupMemberSearch-Wrap">

      <Modal wrapClassName="treeSelectGroupMemberSearch" closable={false} title="" centered width={width} visible={props.isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <div className="treeSelectGroupMemberSearch-top" >
          <Input value={name} onChange={nameOnChange} style={{ height: "28px" }} placeholder="请输入姓名" />
          <Button onClick={searFn} style={{ height: "28px", marginLeft: "10px" }} size="small" type="primary" icon={<SearchOutlined />}>
            搜索
          </Button>
        </div>
        {loading ? <Spin className="spinClass" tip="加载中..." /> : null}
        <div className="treeSelectGroupMemberSearch-wrap">
          <div className="leftTree">
            {/* <LeftTreeView /> */}

            {LeftTreeView()}
          </div>
          <div className="rightUser">
            {
              props.isSelectMultiple ?
                <ShowUserList /> :
                <Checkbox.Group style={{ width: "100%", height: "100%" }} onChange={onChangeCheckbox} >
                  <ShowUserList />
                </Checkbox.Group>
            }

          </div>
        </div>

      </Modal>

    </div >
  )
}

export default treeSelectGroupMemberSearch
